package cn.top.system.service.impl;

import cn.top.model.AjaxResult;
import cn.top.redis.RedisCache;
import cn.top.system.entity.User;
import cn.top.system.service.ILoginService;
import cn.top.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public AjaxResult login(User user) throws Exception {
        Authentication authenticate = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            throw new Exception("认证失败 "+e.getMessage());
        }
        User principal = (User) authenticate.getPrincipal();
        String token = jwtTokenUtil.generateToken(principal);
        String storeKey = "login:" + principal.getId();
        redisCache.setCacheObject(storeKey, principal);

        return AjaxResult.success("认证成功！", token);
    }

    @Override
    public AjaxResult logout() {
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        User principal = (User) authenticationToken.getPrincipal();
        if (Objects.isNull(principal)) {
            throw new RuntimeException("用户未登录");
        }
        redisCache.deleteObject("login:" + principal.getId());
        return AjaxResult.success("注销成功");
    }
}
